define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {
	// 供应商表格数据
	const supplierTableColumns = [
		{
			field: 'id',
			title: '主键',
			align: 'center',
			halign: 'center',
			valign: 'middle',
		},
		{
			field: 'name',
			title: '商品名称',
			align: 'center',
			halign: 'center',
			valign: 'middle',
		},
		{
			field: 'unit',
			title: '单位',
			align: 'center',
			halign: 'center',
			valign: 'middle',
		},
		{
			field: 'price',
			title: '商品单价',
			align: 'center',
			halign: 'center',
			valign: 'middle',
		},
		{
			field: 'nums',
			title: '数量',
			align: 'center',
			halign: 'center',
			valign: 'middle',
		},
		{
			field: 'subtotal',
			title: '小计',
			align: 'center',
			halign: 'center',
			valign: 'middle',
		},
		{
			field: 'typeid',
			title: '商品分类',
			align: 'center',
			halign: 'center',
			valign: 'middle',
		},
		{
			field: 'operate',
			title: __('Operate'),
			align: 'center',
			halign: 'center',
			valign: 'middle',
		},
	];

	// 获取tr结构
	function getTr(data, price, nums, total) {
		const showPrice = price !== void 0 && ((price = Number(price)), true);
		const showNums = nums !== void 0 && ((nums = Number(nums)), true);
		const showTotal = total !== void 0 && ((total = Number(total)), true);

		let html = `
			<tr style="text-align: center; vertical-align: middle;" data-id="${data.id}" class="tr-item">
				<td class="">${data.id}</td>
				<td>${data.name}</td>
				<td>${data.unit.name}</td>
				<td>
					<span style="margin-right: 10px; ${!showPrice ? 'display: none;' : ''} line-height: 26px;" class="tr-price">
						${showPrice ? '￥' + price : ''}
					</span>
					<input name="row[price]" class="tr-input-price" type="number" min="0" ${showPrice ? `value="${price}"` : ''} />
				</td>
				<td>
					<span style="margin-right: 10px; ${!showNums ? 'display: none;' : ''} line-height: 26px;" class="tr-nums">
						${showNums ? nums : ''}
					</span>
					<input name="row[nums]" class="tr-input-nums" type="number" min="0" ${showNums ? `value="${nums}"` : ''} />
				</td>
				<td class="tr-subtotal">${showTotal ? '￥' + total : ''}</td>
				<td>${data.type.name}</td>
				<td>
					<button class="btn btn-danger btn-xs ProDel">删除</button>
				</td>
			</tr>`;

		return html;
	}

	// 获取合计结构
	function getCountHtml(total, price) {
		total = typeof total === 'number' ? total : 0;
		price = typeof price === 'number' ? '￥' + price : '0.00';

		const html = `
			<tr id="product-count" style="text-align: center; vertical-align: middle; ">
				<td>合计</td>
				<td></td>
				<td></td>
				<td></td>
				<td id="product-nums">${total}</td>
				<td id="product-total">${price}</td>
				<td></td>
				<td></td>
			</tr>`;

		return html;
	}

	const controller = {
		index() {
			Table.api.init({
				extend: {
					index_url: 'depot/storage/index' + location.search,
					add_url: 'depot/storage/add',
					edit_url: 'depot/storage/edit',
					del_url: 'depot/storage/del',
					multi_url: 'depot/storage/multi',
					import_url: 'depot/storage/import',
					table: 'depot_storage',
				},
			});

			const table = $('#table');

			table.bootstrapTable({
				// 请求地址
				url: $.fn.bootstrapTable.defaults.extend.index_url,
				// 设置工具栏元素
				toolbar: '.toolbar',
				// 设置主键
				pk: 'id',
				// 排序字段
				sortName: 'createtime',
				// 默认排序方式
				sortOrder: 'desc',
				showExport: false,
				fixedColumns: true,
				fixedRightNumber: 1,
				onLoadSuccess: function () {
					$('.btn-editone').data('area', ['100%', '100%']);

					// 给添加按钮添加`data-area`属性
					$('.btn-add').data('area', ['100%', '100%']);
				},
				// 渲染表格数据
				columns: [
					{
						checkbox: true,
						formatter: function (value, row, index) {
							if (row.status == 1) {
								return { disabled: true };
							} else if (row.status == 2) {
								return { disabled: true };
							} else if (row.status == 3) {
								return { disabled: true };
							}
						},
					},
					{ field: 'id', title: __('Id') },
					{ field: 'code', title: __('Code'), operate: 'LIKE' },
					{ field: 'supplier.name', title: __('Supplierid') },
					{
						field: 'type',
						title: __('Type'),
						searchList: { 1: __('直销入库'), 2: __('退货入库') },
						formatter: Table.api.formatter.normal,
					},
					{ field: 'amount', title: __('Amount'), operate: 'BETWEEN' },
					{
						field: 'createtime',
						title: __('Screatetime'),
						operate: 'RANGE',
						addclass: 'datetimerange',
						autocomplete: false,
						formatter: Table.api.formatter.datetime,
					},
					{
						field: 'status',
						title: __('Status'),
						searchList: { 0: __('待审批'), 1: __('审批失败'), 2: __('待入库'), 3: __('入库完成') },
						formatter: Table.api.formatter.status,
					},
					{
						field: 'operate',
						title: __('Operate'),
						table: table,
						events: Table.api.events.operate,
						formatter: Table.api.formatter.operate,
						buttons: [
							{
								name: 'process',
								title: '通过审核',
								classname: 'btn btn-xs btn-success btn-ajax',
								extend: 'data-toggle="tooltip" data-container="body"',
								icon: 'fa fa-leaf',
								confirm: '确认通过审核吗？',
								url: 'depot/storage/process?status=1',
								success: function (data, ret) {
									$('.btn-refresh').trigger('click');
								},
								error: function (err) {
									console.log(err);
								},
								visible: function (row) {
									return row.status < 1 ? true : false;
								},
							},
							{
								name: 'cancel',
								title: '撤销审核',
								classname: 'btn btn-xs btn-danger btn-ajax',
								extend: 'data-toggle="tooltip" data-container="body"',
								icon: 'fa fa-reply',
								url: 'depot/storage/cancel',
								confirm: '确认要撤回审核吗？',
								success: function (data, ret) {
									$('.btn-refresh').trigger('click');
								},
								error: function (err) {
									console.log(err);
								},
								visible: function (row) {
									if (row.status == 2) {
										return true;
									} else if (row.status == 1) {
										return true;
									}

									return false;
								},
							},
							{
								name: 'pcancel',
								title: '未通过审核',
								classname: 'btn btn-xs btn-info btn-ajax',
								icon: 'fa fa-exclamation-triangle',
								confirm: '确认未通过审核吗？',
								url: 'depot/storage/process?status=0',
								extend: 'data-toggle="tooltip" data-container="body"',
								success: function (data, ret) {
									$('.btn-refresh').trigger('click');
								},
								error: function (err) {
									console.log(err);
								},
								visible: function (row) {
									return row.status < 1 ? true : false;
								},
							},
							{
								name: 'storage',
								title: '确认入库',
								classname: 'btn btn-xs btn-success btn-ajax',
								extend: 'data-toggle="tooltip" data-container="body"',
								icon: 'fa fa-leaf',
								confirm: '确认确认入库吗？',
								url: 'depot/storage/storage',
								success: function (data, ret) {
									$('.btn-refresh').trigger('click');
								},
								error: function (err) {
									console.log(err);
								},
								visible: function (row) {
									return row.status == 2 ? true : false;
								},
							},
							{
								name: 'detail',
								title: '详情',
								classname: 'btn btn-xs btn-success btn-dialog',
								url: 'depot/storage/detail',
								extend: 'data-toggle="tooltip" data-container="body"',
								icon: 'fa fa-eye',
							},
							{
								name: 'edit',
								title: '编辑',
								classname: 'btn btn-xs btn-success btn-editone',
								extend: 'data-toggle="tooltip" data-container="body"',
								icon: 'fa fa-pencil',
								url: 'depot/storage/edit',
								visible: function (row) {
									return row.status == 3 ? false : true;
								},
							},
							{
								name: 'del',
								title: '删除',
								classname: 'btn btn-xs btn-danger btn-delone',
								extend: 'data-toggle="tooltip" data-container="body"',
								icon: 'fa fa-trash',
								visible: function (row) {
									return row.status == 3 ? false : true;
								},
							},
						],
					},
				],
			});

			Table.api.bindevent(table);
		},
		add() {
			const productList = []; // 商品数据
			const productCommitList = []; // 商品提交数据
			const productIds = []; // 商品id

			// id
			// price
			// nums
			// total

			// 添加合计结构
			function addCount() {
				$('#table tbody').html(getCountHtml());
			}

			// 更新合计
			function updateCount() {
				const [nums, total] = productCommitList.reduce(
					(t, item) => {
						t[0] += Number(item.nums);
						t[1] += Number(item.price) * Number(item.nums);

						return t;
					},
					[0, 0]
				);

				$('#product-nums').html(nums);
				$('#product-total').html('￥' + total.toFixed(2));

				setProductCommitList();
			}

			// 设置提交数据
			function setProductCommitList() {
				$('#product-data').val(JSON.stringify(productCommitList));
			}

			// 更新tr结构
			function updateTr(id, price, nums) {
				const tr = $(`.tr-item[data-id="${id}"]`);

				if (price !== void 0) {
					tr.find('.tr-price')
						.html('￥' + price.toFixed(2))
						.css('display', '');
				}

				if (nums !== void 0) {
					tr.find('.tr-nums').html(nums).css('display', '');
				}

				const index = productCommitList.findIndex((v) => Number(v.id) === Number(id));

				if (index !== -1) {
					if (price !== void 0) productCommitList[index].price = price;
					if (nums !== void 0) productCommitList[index].nums = nums;

					let _price = typeof price === 'number' ? price : productCommitList[index].price;
					let _nums = typeof nums === 'number' ? nums : productCommitList[index].nums;

					productCommitList[index].total = _price * _nums;

					tr.find('.tr-subtotal').html('￥' + productCommitList[index].total.toFixed(2));
				}

				updateCount();
			}

			// 初始化商品表格
			$('#table').bootstrapTable({
				columns: supplierTableColumns,
			});

			// 选择供应商
			$('.__select_supplier').on('dblclick', function () {
				Backend.api.open('depot/storage/supplier', '供应商', {
					area: ['80%', '80%'],
					callback: function (data) {
						// 在这里可以接收弹出层中使用`Fast.api.close(data)`进行回传数据

						$('#supplierid').val(data.id);
						$('#c-supplierid').val(data.name);

						$('#c-mobile').val(data.mobile);

						let region_text = data.province_text + data.city_text + data.district_text + data.address;

						$('#c-Region').val(region_text);
					},
				});
			});

			// 添加商品处理函数
			function addProduct() {
				Backend.api.open('depot/storage/product', '商品', {
					area: ['80%', '80%'],
					callback: function (data) {
						if (data) {
							productList.push(data);

							// 判断选择商品是否存在表格里
							if (productIds.includes(data.id)) {
								Backend.api.msg('添加商品已存在');
								return false;
							} else {
								productIds.push(data.id);
							}

							$('#table #product-count').before(getTr(data));

							productCommitList.push({
								id: data.id,
								price: data.price,
								nums: 0,
								total: 0,
							});
						}
					},
				});
			}

			// 添加商品回调
			$('#add-product').click(addProduct);

			// 删除商品
			$('#table').on('click', '.ProDel', function () {
				const id = Number($(this).parents('tr').data('id'));
				let index = -1;

				// 删除自己
				$(this).parents('tr').remove();
				// 从商品列表中删除
				index = productList.findIndex((item) => item.id == id);
				if (index !== -1) productList.splice(index, 1);

				// 从商品提交数据中删除
				index = productCommitList.findIndex((item) => item.id == id);
				if (index !== -1) productCommitList.splice(index, 1);

				index = productIds.findIndex((item) => item == id);
				if (index !== -1) productIds.splice(index, 1);

				updateCount();
			});

			// 单价失去输入事件
			$('#table').on('input', '.tr-input-price', function () {
				// 清除错误提示
				$(this).next().remove();
				const id = Number($(this).parents('tr').data('id'));

				let value = Number($.trim($(this).val()));

				updateTr(id, value, void 0);

				// 判断单价是为空
				if (!value) {
					$(this).after(`<span style="color:red;margin-left:5px;">此处不能为空</span>`);
					return false;
				}

				// 如果输入的值等于0提示
				if (value <= 0) {
					$(this).after(`<span style="color:red;margin-left:5px;">单价不能少1.00</span>`);
					return false;
				}
			});

			// 数量失去输入事件
			$('#table').on('input', '.tr-input-nums', function () {
				// 清除错误提示
				$(this).next().remove();
				const id = Number($(this).parents('tr').data('id'));

				let value = Number($.trim($(this).val()));

				updateTr(id, void 0, value);

				if (!value) {
					$(this).after(`<span style="color:red;margin-left:5px;">此处不能为空</span>`);

					return false;
				}

				if (value <= 0) {
					$(this).after(`<span style="color:red;margin-left:5px;">数量不能少1</span>`);
					return false;
				}
			});

			// 检查输入
			$('button[type="submit"').click(() => {
				const priceList = $('#table .tr-input-price');
				const numsList = $('#table .tr-input-nums');

				for (let i = 0; i < priceList.length; i++) {
					let value = $.trim($(priceList[i]).val());

					// 判断单价是为空
					if (!value) {
						$(priceList[i]).after(`<span style="color:red;margin-left:5px;">此处不能为空</span>`);
						return false;
					}

					// 如果输入的值等于0提示
					if ((value = Number(value)) <= 0) {
						$(priceList[i]).after(`<span style="color:red;margin-left:5px;">单价不能少1.00</span>`);
						return false;
					}
				}

				for (let i = 0; i < numsList.length; i++) {
					let value = $.trim($(numsList[i]).val());

					// 判断单价是为空
					if (!value) {
						$(numsList[i]).after(`<span style="color:red;margin-left:5px;">此处不能为空</span>`);
						return false;
					}

					// 如果输入的值等于0提示
					if ((value = Number(value)) <= 0) {
						$(numsList[i]).after(`<span style="color:red;margin-left:5px;">数量不能少1</span>`);
						return false;
					}
				}

				return true;
			});

			controller.api.bindevent();

			addCount();
		},
		edit() {
			// 选择供应商
			$('.__select_supplier').on('dblclick', function () {
				Backend.api.open('depot/storage/supplier', '供应商', {
					area: ['80%', '80%'],
					callback: function (data) {
						// 在这里可以接收弹出层中使用`Fast.api.close(data)`进行回传数据

						$('#supplierid').val(data.id);
						$('#c-supplierid').val(data.name);

						$('#c-mobile').val(data.mobile);

						let region_text = data.province_text + data.city_text + data.district_text + data.address;

						$('#c-Region').val(region_text);
					},
				});
			});

			const table = $('#table');

			table.bootstrapTable({
				columns: supplierTableColumns,
			});

			// 获取php传过来的数据
			const ProData = Config.Product.productData;

			// 添加商品的数据
			const list = [];

			// 存放商品的数量单价数据
			const ProductList = [];

			// 存放商品的数量单价id
			const Proids = [];

			// 定义删除时，把已在数据库的商品追加到这里
			const DelIds = [];

			// 设置商品数据
			function setProductList() {
				$('#product-data').val(JSON.stringify(ProductList));
			}

			// 设置删除ids
			function setDelId() {
				$('#delproid').val(JSON.stringify(DelIds));
			}

			// 更新合计
			function updateCount() {
				const [nums, total] = ProductList.reduce(
					(t, item) => {
						t[0] += Number(item.nums);
						t[1] += Number(item.price) * Number(item.nums);

						return t;
					},
					[0, 0]
				);

				$('#product-nums').html(nums);
				$('#product-total').html('￥' + total.toFixed(2));

				setProductList();
			}

			// 更新tr结构
			function updateTr(id, price, nums) {
				const tr = $(`.tr-item[data-id="${id}"]`);

				if (price !== void 0) {
					tr.find('.tr-price')
						.html('￥' + price.toFixed(2))
						.css('display', '');
				}

				if (nums !== void 0) {
					tr.find('.tr-nums').html(nums).css('display', '');
				}

				const index = ProductList.findIndex((v) => Number(v.id) === Number(id));

				if (index !== -1) {
					if (price !== void 0) ProductList[index].price = price;
					if (nums !== void 0) ProductList[index].nums = nums;

					let _price = typeof price === 'number' ? price : ProductList[index].price;
					let _nums = typeof nums === 'number' ? nums : ProductList[index].nums;

					ProductList[index].total = _price * _nums;

					tr.find('.tr-subtotal').html('￥' + ProductList[index].total.toFixed(2));
				}

				updateCount();
			}

			if (ProData.length > 0) {
				let TotalCount = 0;
				let NumCount = 0;
				let html = '';

				for (const item of ProData) {
					html += getTr(item.product, item.price, item.nums, item.total);

					list.push(item.product);

					Proids.push(item.product.id);

					ProductList.push({
						pid: item.id,
						id: item.product.id,
						price: item.price,
						nums: item.nums.toString(),
						total: item.total, // 这个是单价*数量
					});

					TotalCount += item.total ? parseFloat(item.total) : 0;

					NumCount += item.nums ? parseInt(item.nums) : 0;
				}

				html += getCountHtml(TotalCount, NumCount);

				setProductList();

				table.find('tbody').html(html);
			}

			// 添加商品回调
			$('#add-product').click(function () {
				Backend.api.open('depot/storage/product', '商品', {
					area: ['80%', '80%'],
					callback: function (data) {
						if (data) {
							list.push(data);

							// 判断选择商品是否存在表格里
							if (Proids.includes(data.id)) {
								Backend.api.msg('添加商品已存在');
								return false;
							} else {
								Proids.push(data.id);
								const index = DelIds.indexOf(Number(data.id))
								if (index !== -1) DelIds.splice(index, 1)
								setDelId()
							}

							$('#table #product-count').before(getTr(data));

							ProductList.push({
								id: data.id,
								price: data.price,
								nums: 0,
								total: 0,
							});
						}
					},
				});
			});

			// 删除商品
			$('#table').on('click', '.ProDel', function () {
				const id = Number($(this).parents('tr').data('id'));
				let index = -1;

				// 删除自己
				$(this).parents('tr').remove();
				// 从商品列表中删除
				index = list.findIndex((item) => item.id == id);
				if (index !== -1) list.splice(index, 1);

				// 从商品提交数据中删除
				index = ProductList.findIndex((item) => item.id == id);
				if (index !== -1) ProductList.splice(index, 1);

				index = Proids.findIndex((item) => item == id);
				if (index !== -1) Proids.splice(index, 1);
				
				DelIds.push(id)
				setDelId();

				updateCount();
			});

			// 单价输入事件
			$('#table').on('input', '.tr-input-price', function () {
				// 清除错误提示
				$(this).next().remove();
				const id = Number($(this).parents('tr').data('id'));

				let value = Number($.trim($(this).val()));

				updateTr(id, value, void 0);

				// 判断单价是为空
				if (!value) {
					$(this).after(`<span style="color:red;margin-left:5px;">此处不能为空</span>`);
					return false;
				}

				// 如果输入的值等于0提示
				if (value <= 0) {
					$(this).after(`<span style="color:red;margin-left:5px;">单价不能少1.00</span>`);
					return false;
				}
			});

			// 数量输入事件
			$('#table').on('input', '.tr-input-nums', function () {
				// 清除错误提示
				$(this).next().remove();
				const id = Number($(this).parents('tr').data('id'));

				let value = Number($.trim($(this).val()));

				updateTr(id, void 0, value);

				if (!value) {
					$(this).after(`<span style="color:red;margin-left:5px;">此处不能为空</span>`);

					return false;
				}

				if (value <= 0) {
					$(this).after(`<span style="color:red;margin-left:5px;">数量不能少1</span>`);
					return false;
				}
			});

			// 检查输入
			$('button[type="submit"').click(() => {
				const priceList = $('#table .tr-input-price');
				const numsList = $('#table .tr-input-nums');

				for (let i = 0; i < priceList.length; i++) {
					let value = $.trim($(priceList[i]).val());

					// 判断单价是为空
					if (!value) {
						$(priceList[i]).after(`<span style="color:red;margin-left:5px;">此处不能为空</span>`);
						return false;
					}

					// 如果输入的值等于0提示
					if ((value = Number(value)) <= 0) {
						$(priceList[i]).after(`<span style="color:red;margin-left:5px;">单价不能少1.00</span>`);
						return false;
					}
				}

				for (let i = 0; i < numsList.length; i++) {
					let value = $.trim($(numsList[i]).val());

					// 判断单价是为空
					if (!value) {
						$(numsList[i]).after(`<span style="color:red;margin-left:5px;">此处不能为空</span>`);
						return false;
					}

					// 如果输入的值等于0提示
					if ((value = Number(value)) <= 0) {
						$(numsList[i]).after(`<span style="color:red;margin-left:5px;">数量不能少1</span>`);
						return false;
					}
				}

				return true;
			});

			controller.api.bindevent();
		},
		supplier() {
			Table.api.init({});

			const supplierTable = $('#supplier-table');

			supplierTable.bootstrapTable({
				url: 'depot/storage/supplier',
				pk: 'id',
				sortName: 'createtime',
				sortOrder: 'desc',
				search: false,
				showExport: false,
				commonSearch: false,
				showColumns: false,
				showToggle: false,
				columns: [
					{ field: 'id', title: __('Id') },
					{ field: 'name', title: __('Name'), operate: 'LIKE' },
					{ field: 'mobile', title: __('Mobile'), operate: 'LIKE' },
					{
						field: 'createtime',
						title: __('Createtime'),
						operate: 'RANGE',
						addclass: 'datetimerange',
						autocomplete: false,
						formatter: Table.api.formatter.datetime,
					},
					{ field: 'province_text', title: __('Province'), operate: 'LIKE' },
					{ field: 'city_text', title: __('City'), operate: 'LIKE' },
					{ field: 'district_text', title: __('District'), operate: 'LIKE' },
					{ field: 'address', title: __('Address'), operate: 'LIKE' },
					{
						field: 'operate',
						title: __('Operate'),
						table: supplierTable,
						events: Table.api.events.operate,
						formatter: Table.api.formatter.operate,
						buttons: [
							{
								name: 'chapter',
								text: '选择',
								title: '选择',
								classname: 'btn btn-primary btn-xs select-supplier-btn',
							},
						],
					},
				],
			});

			// 点击选择回调
			supplierTable.on('click', '.select-supplier-btn', function () {
				let index = $(this).parents('tr').data('index');

				let data = Table.api.getrowdata(supplierTable, index);

				Backend.api.close(data);
			});

			controller.api.bindevent();
		},
		product: function () {
			// 初始化表格
			Table.api.init({});

			const productTable = $('#product-table');

			productTable.bootstrapTable({
				url: 'depot/storage/product',
				pk: 'id',
				sortName: 'product.id',
				search: false,
				showExport: false,
				commonSearch: false,
				showColumns: false,
				showToggle: false,
				columns: [
					{ field: 'id', title: __('Id') },
					{ field: 'name', title: __('Name'), operate: 'LIKE' },
					{
						field: 'flag',
						title: __('Flag'),
						searchList: { 1: __('新品'), 2: __('热销'), 3: __('推荐') },
						formatter: Table.api.formatter.flag,
					},
					{
						field: 'status',
						title: __('Status'),
						searchList: { 0: __('下架'), 1: __('上架') },
						formatter: Table.api.formatter.flag,
					},
					{ field: 'stock', title: __('Stock') },
					{ field: 'type.name', title: __('Typeid') },
					{ field: 'unit.name', title: __('Unitid') },
					{
						field: 'createtime',
						title: __('Createtime'),
						operate: 'RANGE',
						addclass: 'datetimerange',
						autocomplete: false,
						formatter: Table.api.formatter.datetime,
					},
					{
						field: 'operate',
						title: __('Operate'),
						table: productTable,
						events: Table.api.events.operate,
						formatter: Table.api.formatter.operate,
						buttons: [
							{
								name: 'chapter',
								text: '选择',
								title: '选择',
								classname: 'btn btn-primary btn-xs select-product',
							},
						],
					},
				],
			});

			productTable.on('click', '.select-product', function () {
				let index = $(this).parents('tr').data('index');

				let data = Table.api.getrowdata(productTable, index);

				Backend.api.close(data);
			});
		},
		api: {
			// JS模块化的全局方法
			bindevent: function () {
				Form.api.bindevent($('form[role=form]'));
			},
		},
	};

	return controller;
});
